const ws = require('nodejs-websocket')

//负责登陆服务器消息管理的模块
class HallMessageMgr{
    constructor() {
    }
    static getInstance() {
        if(!HallMessageMgr.instance){
            HallMessageMgr.instance = new HallMessageMgr();
            return HallMessageMgr.instance;
        }else{
            return HallMessageMgr.instance;
        }
    }
    //创建服务并监听  port-> 端口号
    createServer(port){
        let websocket =  ws.createServer((client)=>{
            client.on('text',(result)=>{
                let message = JSON.parse(result);
                let type = message.type;
                let data = message.data;
                this.recvMessaage(type,data,client);
                console.log('大厅服务器接收到消息；消息类型->',type,'，数据为->',data);
                //client.send("你好啊客户端")
            })
            client.on('error',(err)=>{
                console.log('连接出现错误',err)
            })
            client.on('close',()=>{
                console.log('连接断开');
            })
        })
        websocket.listen(port);
        console.log('大厅服务器启动，端口号为：',port);
    }
    //接收客户端消息并处理 type--消息类型  data--传递的数据  client--某个客户端
    recvMessaage(type,data,client){
        switch(type){
            case 'create_room':
                this.responseCreateRoomMessage(type,data,client);
                break;
            case 'join_room':
                this.responseJoinRoomMessagage(type,data,client);
                break;
            default:
                break;
        }
    }
    //发送给客户端消息 type--消息类型  data--传递的数据  client--某个客户端
    sendMessage(type,data,client){
        let result = {
            type:type,
            data:data,
        }
        client.send(JSON.stringify(result));
    }
    //响应客户端创建房间请求
    async responseCreateRoomMessage(type,room_info,client){
        let room_id = await this.getNewRoomId();  //获取可用的房间ID
        console.log('roomId = ',room_id,'  房间信息 = ',room_info); //获取创建房间的股则
        global.hallServerMgr.hallDbMgr.saveRoomInfo(room_id,room_info).then(()=>{
            let result = {
                type:type,
                data:room_id,
            }
            client.send(JSON.stringify(result));
        }).catch(()=>{
            let result = {
                type:type,
                data:0,
            }
            client.send(JSON.stringify(result));
        })
    }

    //获取新的房间ID .then
    getNewRoomId(){
        return new Promise((resolve, reject) => {
            this.getValidRoomID(resolve);
        })
    }
    //获取一个有效的ID
    getValidRoomID(callback){
        let str = '';
        for(let i = 0; i <6; i++){
            if(i === 0){
                //            随机获取一个0-9的字符
                let tmpStr = Math.round(Math.random()*9);
                if(tmpStr !==0){
                    str += tmpStr;
                    continue;
                }else{
                    str += 1;
                }
            }
            str += Math.round(Math.random()*9);
        }

        global.hallServerMgr.hallDbMgr.queryRoomIdIsUsable(str * 1).then((result)=>{
            if(result.length > 0){
                this.getValidRoomID(callback);
            }else{
                if(callback){
                    callback(str);
                }
            }
        }).catch((err)=>{
            this.getValidRoomID(callback);
        })
    }


    async responseJoinRoomMessagage(type,data,client){
        let roomID = data.roomID;
        let result = await global.hallServerMgr.hallDbMgr.getRoomInfo(roomID);

        let sendData = {
            type:type,
            data:JSON.stringify(result[0]),
        }

        client.send(JSON.stringify(sendData));
    }

}

module.exports = HallMessageMgr.getInstance();
